package com.fengkai.filepost.pdfoutstream.test.ODsolutions;

import java.util.Arrays;

/**
 * @author Fengkai  最小分组结果
 * @creat 2023/3/29
 */
public class MinGroup {
    public static void main (String[] args) {
        for (int i = 0; i < 100; i++) {
            Integer maxValue = (int) (Math.random()*100 + 1);
            int[] ints1 = new int[(int) (Math.random()*100 + 1)];
            for (int j = 0; j < ints1.length; j++) {
                ints1[j] =  (int) (Math.random()*maxValue + 1);
            }
            System.out.println(myMinGroup(maxValue, ints1) == getCheck(maxValue, ints1));
        }

    }

    private  static int  myMinGroup (int maxValue, int[] ints) {
        int minGroup = 0;
        Arrays.sort(ints);
        int left = 0; //左指针
        int right = ints.length - 1;  //右指针

        while (left <= right) {
            if (Integer.valueOf(left).equals(right) ){
                minGroup ++;
                break;
            }else if (ints[left] + ints[right] <= maxValue){
                right --;
                left ++;
                minGroup ++;
            }else {
                right --;
                minGroup ++;
            }
        }
        return minGroup;
    }

    public static int getCheck(int maxValue, int[] ints) {
        try {

            // 排序
            Arrays.sort(ints);
            int result = 0;
            int a = 0;
            int b = ints.length - 1;
            while (b >= a) {
                if (Integer.valueOf(a).equals(b)) {
                    ++result;
                    break;
                }
                if (ints[b] + ints[a] <= maxValue) {
                    ++result;
                    a++;
                    --b;
                } else {
                    --b;
                    ++result;
                }
            }
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("input error");
        }
        return 0;
    }
}
